package com.hs.pre.page;

public class SearchPageUtil {
    
	private static final String PREVIOUS_PAGE = "上一页";
	private static final String NEXT_PAGE = "下一页";
	private  String url="/app/pre/search.do";
	public  void setUrl(String newUrl){
		url = newUrl;
	}
	public SearchPageUtil(){ 
	}
	/**
	 * 搜索结果分页
	 * @param basePath 请求路径
	 * @param allNum   结果总数
	 * @param pageNum  每页显示数量
	 * @param start    起始页
	 * @param paramStr 参数串
	 * @return
	 */
	public  String getPageStr(String basePath,String allNum,String pageNum,String start,String paramStr){
		StringBuilder buffer = new StringBuilder();
		int defaultPageNum = 10;
		if(null == start ||"".equalsIgnoreCase(start) || "null".equalsIgnoreCase(start))
			start = "0";
		int startNum = Integer.parseInt(start);
		int allCount = Integer.parseInt(allNum);
		int pageCount = Integer.parseInt(pageNum);
		
		if(allCount < pageCount)
			return "";
		//当前起始页数除以每页显示的数量得出当前是第几页
		int  currentPage = startNum / pageCount +1;
		buffer.append("<TABLE id=nav align=center><TBODY><TR vAlign=top>\n");
		if(startNum != 0){
			int prestart = (currentPage-2) * pageCount ;
			buffer.append(" <TD class=b><A href=\"" + basePath +url+"?q=" + paramStr + "&start=" + prestart + "\"><SPAN id=np></SPAN><B>上一页</B></A>\n");
		} 
		int pages = allCount/pageCount == 0?1:allCount/pageCount;
		if( pages != 1){
			if(pages >= defaultPageNum){
				for(int i = 0;i < defaultPageNum;i++){
					int prestart = i * pageCount ;
					int currentNextPage = currentPage * pageCount;
					if(currentPage == (i+1))
						buffer.append("<TD class=cur><SPAN id=nc></SPAN>"+(i+1)+"\n");
					else
						buffer.append("<TD><A href=\"" + basePath + url+"?q=" + paramStr + "&start=" + prestart + "\"><SPAN class=nr></SPAN>"+(i+1)+"</A>\n");
					//最后添加最后一页按钮
					if(i == defaultPageNum - 1 ){
						buffer.append(" <TD class=b><A href=\"" + basePath + url+"?q=" + paramStr + "&start=" + currentNextPage  + "\"><SPAN id=np></SPAN><B>下一页</B></A>\n");
					}
				}
				
			} else{
				
				for(int i = 0;i < pages;i++){
					int prestart = i * pageCount ;
					int currentNextPage = currentPage * pageCount;
					if(currentPage == (i+1))
						buffer.append("<TD class=cur><SPAN id=nc></SPAN>"+(i+1)+"\n");
					else{ 
						buffer.append("<TD><A href=\"" + basePath + url+"?q=" + paramStr + "&start=" + prestart + "\"><SPAN class=nr></SPAN>"+(i+1)+"</A>\n");
					}
					//最后添加最后一页按钮
					if(i != 0 && i == pages - 1 ){
						buffer.append(" <TD class=b><A href=\"" + basePath + url+"?q="+ paramStr + "&start=" + currentNextPage + "\"><SPAN id=np></SPAN><B>下一页</B></A>\n");
					}
				}
			}
		}
		buffer.append("</TR></TBODY></TABLE>");
		return buffer.toString();
	}
	
	public static void main(String[] args){
		//System.out.println(getPageStr("test","300","24","72","fangming=11"));
	}
}
